package com.topfinance.cmt;

import java.util.HashMap;
import java.util.Map;

public class CMTMsgParse {
	public static String[][] getMsgInfo(String msgType) {
		Map msgMap = CMTMsgDef.getCMTMsgMap();
		String[][] msgInfo = (String[][]) msgMap.get(msgType);
		return msgInfo;
	}

	public static Map unPackItem(String[] msgInfoRow, String msgBody) {
		String tagValue = msgInfoRow[0];
		String itemName = msgInfoRow[1];
		String itemDefine = msgInfoRow[2];
		String itemFlag = msgInfoRow[3];
		String itemType = msgInfoRow[4];
		String itemLength = msgInfoRow[5];
		int index = 0;
		index = msgBody.indexOf(":" + tagValue);
		int length = Integer.valueOf(itemLength).intValue();
		int endIndex = index + 5 + length;
		if (endIndex > msgBody.length()) {
			endIndex = msgBody.length();
		}
		String subString1 = msgBody.substring(index, endIndex);
		String subString2 = subString1.substring(5);
		int itemValueEnd = subString2.indexOf(":");
		String itemValue = "";
		if (itemValueEnd > 0) {
			itemValue = subString2.substring(0, itemValueEnd);
		} else {
			itemValue = subString2;
		}
		Map itemMap = new HashMap();
		itemMap.put("tagValue", tagValue);
		itemMap.put("itemName", itemName);
		itemMap.put("itemDefine", itemDefine);
		itemMap.put("itemFlag", itemFlag);
		itemMap.put("itemType", itemType);
		itemMap.put("itemLength", itemLength);
		itemMap.put("itemValue", itemValue);
		System.out.println(tagValue + "," + itemType + "," + itemValue);
		return itemMap;

	}

	public static Map unPackMsg(String msgType, String msgBody) {
		Map msgMap = new HashMap();
		String[][] msgInfo = getMsgInfo(msgType);
		int size = msgInfo.length;
		for (int i = 0; i < size; i++) {
			String[] msgInfoRow = msgInfo[i];
			Map itemMap = new HashMap();
			itemMap = unPackItem(msgInfoRow, msgBody);
			String tagValue = msgInfoRow[0];
			msgMap.put(tagValue, itemMap);
		}
		return msgMap;
	}

	public static String packItem(String[] msgInfoRow, Map msgMap) {
		String tagValue = msgInfoRow[0];
		String itemName = msgInfoRow[1];
		String itemDefine = msgInfoRow[2];
		String itemFlag = msgInfoRow[3];
		String itemType = msgInfoRow[4];
		String itemLength = msgInfoRow[5];
		Map rowMap = (Map) msgMap.get(tagValue);
		String itemValue = (String) rowMap.get("itemValue");
		String totalValue = "";
		totalValue = ":" + tagValue + ":" + itemValue;
		System.out.println(totalValue);
		return totalValue;

	}

	public static String packMsg(String msgType, Map msgMap) {
		StringBuffer sb = new StringBuffer();
		String[][] msgInfo = getMsgInfo(msgType);
		int size = msgInfo.length;
		for (int i = 0; i < size; i++) {
			String[] msgInfoRow = msgInfo[i];
			String itemStr = packItem(msgInfoRow, msgMap);
			sb.append(itemStr);
		}
		System.out.println(sb.toString());
		return sb.toString();
	}
}
